/**
 * 
 */
package org.dse.html.processor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dse.html.TagName;
import org.dse.html.TagResultContainer;

/**
 * This class is used to process the hyperlink content.
 * 
 * It is configged in the application context and added into the
 * TagProcessorContainer singleton.
 * 
 * @author zhangchen
 * 
 */
public class LinkTagProcessor implements TagProcessor {

	private static final String regStr = "<a\\s+href\\s*=\\s*"// <a href=
			+ "(\"[^\"]*\"|[^\\s]*)" // URL part
			+ "[^>]*?>";// other parts

	private static Pattern ptn = Pattern.compile(regStr,
			Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);

	/**
	 * Process a link tag.
	 * 
	 * @param htmlContent
	 *            the whole content of current processed html document
	 * @param index
	 *            the start index of the current tag
	 * @param container
	 *            the TagResultContainer which the processor sends results to
	 */
	public void processTag(String htmlContent, int index,
			TagResultContainer container) {
		Matcher matcher = ptn.matcher(htmlContent);
		if (matcher.find(index)) {
			String link = matcher.group(1);// get the hyper link url
			if (link.length() != 0 && link.charAt(0) == '\"'
					|| link.charAt(0) == '\'')
				link = link.substring(1, link.length() - 1);

			if (link.length() != 0 && link.charAt(0) != '#'
					&& !link.startsWith("javascript:")
					&& !link.startsWith("mailto:"))
				// add to result container with tag name "a"
				container.addResult(TagName.LINK_TAG_NAME, link);
		}
	}
}
